package com.youkeyi.ddy.cloud.basic.storage.category.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youkeyi.ddy.cloud.basic.storage.category.entity.SysCategory;
import com.youkeyi.ddy.cloud.basic.storage.category.service.SysCategoryService;
import com.youkeyi.ddy.cloud.common.api.basic.storage.category.StorageCategoryCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.storage.category.dto.StorageCategoryListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.storage.category.dto.StorageCategoryListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.storage.category.param.StorageCategoryCreateCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.storage.category.param.StorageCategoryDeleteCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.storage.category.param.StorageCategoryQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.storage.category.param.StorageCategoryUpdateCloudParam;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyCloudBasicPublicConstant;
import com.youkeyi.ddy.cloud.common.enums.ResponseCodeEnum;
import com.youkeyi.ddy.cloud.common.response.ResponseContent;
import com.youkeyi.ddy.cloud.common.utils.SimpleUUidUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商品分类 前端控制器
 * </p>
 *
 * @author xiawang.liu
 * @since 2024-04-18
 */
@Service
public class SysCategoryController implements StorageCategoryCloudService {
    
    @Autowired
    private SysCategoryService sysCategoryService;

    @Override
    public StorageCategoryListCloudDto query(StorageCategoryQueryCloudParam param) {
        StorageCategoryListCloudDto dto = new StorageCategoryListCloudDto();
        if (null == param) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }

        if (CollectionUtils.isNotEmpty(param.getCategoryPrimaryKeys())) {
            param.getCategoryPrimaryKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getCorpKeys())) {
            param.getCorpKeys().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getCodes())) {
            param.getCodes().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getNames())) {
            param.getNames().removeAll(Collections.singleton(null));
        }
        if (CollectionUtils.isNotEmpty(param.getParentKeys())) {
            param.getParentKeys().removeAll(Collections.singleton(null));
        }

        QueryWrapper<SysCategory> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .in(CollectionUtils.isNotEmpty(param.getCategoryPrimaryKeys()), SysCategory::getPrimaryKey, param.getCategoryPrimaryKeys())
                .in(CollectionUtils.isNotEmpty(param.getCorpKeys()), SysCategory::getCorpKey, param.getCorpKeys())
                .in(CollectionUtils.isNotEmpty(param.getNames()), SysCategory::getName, param.getNames())
                .like(StringUtils.isNotBlank(param.getNameFuzzy()), SysCategory::getName, param.getNameFuzzy())
                .in(CollectionUtils.isNotEmpty(param.getCodes()), SysCategory::getCode, param.getCodes())
                .like(StringUtils.isNotBlank(param.getCodeFuzzy()), SysCategory::getCode, param.getCodeFuzzy())
                .in(CollectionUtils.isNotEmpty(param.getParentKeys()), SysCategory::getParentKey, param.getParentKeys())
                .eq(null != param.getLevel(), SysCategory::getLevel, param.getLevel())
                .ne(SysCategory::getIsDeleted, YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value())
        ;

        Page<SysCategory> page = new Page<>();
        if (null != param.getCurrentPage() && null != param.getPageSize()) {
            page.setCurrent(param.getCurrentPage());
            page.setSize(param.getPageSize());
        } else {
            page.setCurrent(1);
            page.setSize(99999999);
        }
        Page<SysCategory> categoryList = sysCategoryService.page(page, wrapper);
        if (CollectionUtils.isNotEmpty(categoryList.getRecords())) {
            dto.setTotal(categoryList.getTotal());

            List<StorageCategoryListItemCloudDto> items = new ArrayList<>();
            categoryList.getRecords().forEach(category -> {
                StorageCategoryListItemCloudDto item = new StorageCategoryListItemCloudDto();
                item.setCategoryPrimaryKey(category.getPrimaryKey());
                item.setCorpKey(category.getCorpKey());
                item.setName(category.getName());
                item.setCode(category.getCode());
                item.setLevel(category.getLevel());
                item.setParentKey(category.getParentKey());
                item.setParentName(category.getParentName());
                item.setPropertyKey(category.getPropertyKey());
                item.setPath(category.getPath());
                item.setDesc(category.getDesc());
                item.setRemark(category.getRemark());
                item.setIsDeleted(category.getIsDeleted());
                item.setIsDeletedName(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO.getName(item.getIsDeleted()));
                item.setCreateTime(category.getCreateTime() != null ? category.getCreateTime().getTime() : null);
                item.setCreateUserKey(category.getCreateUserKey());
                item.setCreateUserName(category.getCreateUserName());
                item.setUpdateTime(category.getUpdateTime() != null ? category.getUpdateTime().getTime() : null);
                item.setUpdateUserKey(category.getUpdateUserKey());
                item.setUpdateUserName(category.getUpdateUserName());
                items.add(item);
            });
            dto.setRows(items);
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }

    @Override
    public ResponseContent create(StorageCategoryCreateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param
                || StringUtils.isBlank(param.getName()) || StringUtils.isBlank(param.getCode())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }
        SysCategory category = new SysCategory();
        category.setPrimaryKey(SimpleUUidUtils.getUuid());
        category.setCorpKey(param.getCorpKey());
        category.setName(param.getName());
        category.setCode(StringUtils.isNotBlank(param.getCode()) ? param.getCode() : String.format("SERVER-%s", System.currentTimeMillis()));
        category.setPropertyKey(param.getPropertyKey());
        category.setDesc(param.getDesc());
        category.setRemark(param.getRemark());
        category.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_NO.value());
        category.setCreateUserKey(param.getCreateUserKey());
        category.setCreateUserName(param.getCreateUserName());
        category.setCreateTime(new Date());

        // 构造父级数据
        category.setLevel(0);
        category.setParentKey("");
        category.setParentName("");
        category.setPath(String.format("|%s|", category.getPrimaryKey()));
        if (StringUtils.isNotBlank(param.getParentKey())) {
            QueryWrapper<SysCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysCategory::getPrimaryKey, param.getParentKey());
            SysCategory parentCategory = sysCategoryService.getOne(queryWrapper);
            if (null != parentCategory && StringUtils.isNotBlank(parentCategory.getPrimaryKey())) {
                category.setLevel(parentCategory.getLevel() + 1);
                category.setParentKey(parentCategory.getPrimaryKey());
                category.setParentName(parentCategory.getName());
                category.setPath(String.format("%s|", parentCategory.getPath()));
            }
        }

        boolean save = sysCategoryService.save(category);
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
            return rc;
        }
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        rc.setKey(category.getPrimaryKey());
        return rc;
    }

    @Override
    public ResponseContent update(StorageCategoryUpdateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || StringUtils.isBlank(param.getCategoryPrimaryKey())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }


        QueryWrapper<SysCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysCategory::getPrimaryKey, param.getCategoryPrimaryKey());
        SysCategory myselfCategory = sysCategoryService.getOne(queryWrapper);
        if (null == myselfCategory || StringUtils.isBlank(myselfCategory.getPrimaryKey())) {
            rc.setErrorMessage(ResponseCodeEnum.UNKNOWN_ERROR.getMessage());
            return rc;
        }


        UpdateWrapper<SysCategory> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .eq(SysCategory::getPrimaryKey, param.getCategoryPrimaryKey());
        SysCategory category = new SysCategory();
        category.setPrimaryKey(param.getCategoryPrimaryKey());
        category.setName(param.getName());
        category.setCode(param.getCode());
        category.setPropertyKey(param.getPropertyKey());
        category.setDesc(param.getDesc());
        category.setRemark(param.getRemark());
        category.setUpdateUserKey(param.getUpdateUserKey());
        category.setUpdateUserName(param.getUpdateUserName());
        category.setUpdateTime(new Date());

        if (!myselfCategory.getParentKey().equals(param.getParentKey())) {
            // 构造父级数据
            category.setLevel(0);
            category.setParentKey("");
            category.setParentName("");
            category.setPath(String.format("|%s|", category.getPrimaryKey()));
            if (StringUtils.isNotBlank(param.getParentKey())) {
                QueryWrapper<SysCategory> queryParentWrapper = new QueryWrapper<>();
                queryParentWrapper.lambda().eq(SysCategory::getParentKey, param.getParentKey());
                SysCategory parentCategory = sysCategoryService.getOne(queryParentWrapper);
                if (null != parentCategory && StringUtils.isNotBlank(parentCategory.getPrimaryKey())) {
                    category.setLevel(parentCategory.getLevel() + 1);
                    category.setParentKey(parentCategory.getPrimaryKey());
                    category.setParentName(parentCategory.getName());
                    category.setPath(String.format("%s|", parentCategory.getPath()));
                }
            }
        }

        boolean save = sysCategoryService.update(category, wrapper);
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
            return rc;
        }
        return rc;
    }

    @Override
    public ResponseContent delete(StorageCategoryDeleteCloudParam param) {
        ResponseContent rc = new ResponseContent();
        if (null == param || CollectionUtils.isEmpty(param.getCategoryPrimaryKeys())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }
        UpdateWrapper<SysCategory> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .in(SysCategory::getPrimaryKey, param.getCategoryPrimaryKeys());

        SysCategory category = new SysCategory();
        category.setIsDeleted(YoukeyiDdyCloudBasicPublicConstant.SYSTEM_YES_OR_NO_YES.value());
        category.setUpdateUserKey(param.getUpdateUserKey());
        category.setUpdateUserName(param.getUpdateUserName());
        category.setUpdateTime(new Date());
        boolean save = sysCategoryService.update(category, wrapper);
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        if (!save) {
            rc.setErrorMessage(ResponseCodeEnum.FAIL.getMessage());
        }
        return rc;
    }
}
